package com.dzirtbry.MedicineAnalizer.Types;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

public abstract class AbstractSaveableList<T extends Serializable> extends ArrayList<T> implements Saveable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3570807833883037605L;
	
	@Override
	public void save(String filename) throws IOException {
		FileOutputStream fileStream = new FileOutputStream(new File(filename));
		ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
		objectStream.writeInt(this.size());
		for (Serializable obj: this) {
			objectStream.writeObject(obj);
		}
		objectStream.close();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void load(String filename) throws IOException, ClassNotFoundException {
		FileInputStream fileInputStream = new FileInputStream(new File(filename));
		ObjectInputStream objectStream = new ObjectInputStream(fileInputStream);
		int size = objectStream.readInt();
		for (int i=0; i<size; i++) {
			this.add((T) objectStream.readObject());
		}
		objectStream.close();
	}
}
